<template>
  <div class="f-box">
    <a-form :form="form">
      <a-row>
        <a-col :span="24">
          <a-row type="flex" justify="space-between">
            <a-col :span="11">
              <a-form-item label="合同名称">
                <a-input
                  v-decorator="['name', { initialValue: defaultVal.name }]"
                  allowClear
                  style="width: 100%"
                  placeholder="请输入"
                  :maxLength="80"
                />
              </a-form-item>
            </a-col>
            <a-col :span="11">
              <a-form-item label="合同类型">
                <a-select
                  style="width: 100%"
                  v-decorator="['type', { initialValue: defaultVal.type || undefined }]"
                  show-search
                  allowClear
                  :filter-option="filterOption"
                  :disabled="getDisabled(defaultVal.contractId)"
                  @change="changeType"
                  placeholder="请选择"
                >
                  <a-select-option :value="item.id" v-for="(item, index) in typeList" :key="index"> {{ item.name }} </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="11" v-if="show">
              <a-form-item label="合同期限">
                <a-row type="flex" justify="space-between">
                  <a-col :span="11">
                    <a-form-item>
                      <a-select
                        style="width: 100%"
                        @change="change1"
                        v-decorator="[`termYear`, { initialValue: gettermValue(defaultVal) || undefined }]"
                        allowClear
                        show-search
                        :disabled="getDisabled(defaultVal.contractId)"
                        :filter-option="filterOption"
                        placeholder="请选择"
                      >
                        <a-select-option :value="item" v-for="(item, index) in 12" :key="index"> {{ item }} </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col :span="11">
                    <a-form-item>
                      <a-select
                        style="width: 100%"
                        v-decorator="[
                          'timeLimitType',
                          {
                            initialValue: gettimeLimitType(defaultVal)
                          }
                        ]"
                        show-search
                        :disabled="getDisabled(defaultVal.contractId)"
                        :filter-option="filterOption"
                        placeholder="请选择"
                        @change="change3"
                      >
                        <a-select-option :value="item.id" v-for="(item, index) in timeList" :key="index"> {{ item.name }} </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-row>
              </a-form-item>
            </a-col>

            <a-col :span="11">
              <a-form-item label="合同开始时间">
                <a-date-picker
                  :disabled="getDisabled(defaultVal.contractId)"
                  v-decorator="['startTime', { initialValue: getMoment(defaultVal.startTime) }]"
                  @change="change2"
                />
              </a-form-item>
            </a-col>
            <a-col :span="11" v-if="show">
              <a-form-item label="合同结束时间">
                <a-date-picker
                  :disabled="getDisabled(defaultVal.contractId)"
                  v-decorator="['endTime', { initialValue: getMoment(defaultVal.endTime) }]"
                  @change="change2"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="合同备注">
            <a-textarea
              style="width: 100%"
              allowClear
              :maxLength="255"
              :auto-size="{ minRows: 8, maxRows: 15 }"
              v-decorator="['remark', { initialValue: defaultVal.remark }]"
            />
          </a-form-item>
          <a-form-item class="mr24" style="text-align: center">
            <a-button type="primary" @click="handleSubmit" :loading="loading"> 保存 </a-button>
            <a-button class="ml12" @click="$emit('upDate', index, false)"> 取消 </a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script>
import { updateEmpContracts, addEmpContracts } from "@/api/staff/staff";
const typeList = [
  { id: "laborContractLimit", name: "固定期限劳动合同" },
  { id: "laborContractUnlimit", name: "无固定期限劳动合同" },
  { id: "laborContractJobs", name: "以完成一定工作任务为期限的劳动合同" },
  { id: "internAccords", name: "实习协议" },
  { id: "laborContract", name: "劳务合同" },
  { id: "reemployAccords", name: "返聘协议" },
  { id: "laborContractDispatch", name: "劳务派遣合同" },
  { id: "borrowedContract", name: "借调合同" },
  { id: "engagementLetter", name: "约定书" },
  { id: "partTime", name: "兼职合同" },
  { id: "noviciateAgreement", name: "见习协议" },
  { id: "dimissionContract", name: "离职合同" },
  { id: "retireReEmploy", name: "退休返聘合同" },
  { id: "other", name: "其它" }
];
const timeList = [
  { id: 1, name: "年" },
  { id: 2, name: "月" }
];
export default {
  props: {
    index: {
      type: Number,
      default: -1
    },
    employInfoId: {
      type: String,
      default: ""
    },
    defaultVal: {
      type: Object,
      default: () => {}
    }
  },

  data() {
    return {
      typeList,
      timeList,
      form: this.$form.createForm(this, {}),
      loading: false,
      show: true
    };
  },
  created() {
    if (this.index !== -1) this.show = this.defaultVal.type !== "laborContractUnlimit";
  },
  methods: {
    async onPostAddEmpContracts(v) {
      try {
        await addEmpContracts({
          ...v,
          id: null,
          empId: this.employInfoId,
          companyId: this.$store.state.hr.companyId
        });
        this.$notification.success({ message: "操作成功" });
        this.loading = false;
        this.$emit("upDate", this.index, true);
      } catch (err) {
        console.log("error log --> ", err);
        this.loading = false;
      }
    },
    async onPutUpdateEmpContracts(v) {
      try {
        await updateEmpContracts({
          ...v,
          id: this.defaultVal.id,
          empId: this.employInfoId,
          companyId: this.$store.state.hr.companyId
        });
        this.$notification.success({ message: "操作成功" });
        this.loading = false;
        this.$emit("upDate", this.index, true);
      } catch (err) {
        console.log("error log --> ", err);
        this.loading = false;
      }
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (values.endTime && values.startTime && values.endTime < values.startTime) {
            this.$notification["error"]({
              message: "合同结束日期不得早于开始日期"
            });
            return;
          }
          if (!values.name) values.name = "未命名合同";
          if (values.startTime && typeof values.startTime !== "string") {
            values.startTime = this.moment(values.startTime).format("YYYY-MM-DD");
          }
          if (values.endTime && typeof values.endTime !== "string") values.endTime = this.moment(values.endTime).format("YYYY-MM-DD");
          if (values.timeLimitType === 1) values["termMonth"] = 0;
          if (values.timeLimitType === 2) {
            values.termMonth = values.termYear;
            values.termYear = 0;
          }
          this.loading = true;
          this.index === -1 ? this.onPostAddEmpContracts(values) : this.onPutUpdateEmpContracts(values);
        }
      });
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },
    gettermValue(item) {
      if (item.termYear) {
        return item.termYear;
      } else if (item.termMonth) {
        return item.termMonth;
      } else if (item.termDay !== null) {
        return item.termDay;
      }
    },
    gettimeLimitType(item) {
      if (item.termYear) {
        return 1;
      } else if (item.termMonth) {
        return 2;
      } else if (item.termDay) {
        return 3;
      }
      return 1;
    },
    change1() {
      setTimeout(() => {
        const values = this.form.getFieldsValue();
        if (values.termYear && values.startTime) {
          if (values.timeLimitType === 1) {
            // 年
            values.endTime = this.afterYear(values.startTime, values.termYear);
          } else if (values.timeLimitType === 2) {
            // 月
            values.endTime = this.afterMonth(values.startTime, values.termYear);
          }
        } else {
          values.endTime = null;
        }
        this.form.setFieldsValue({ ...values });
      });
    },
    change3(e) {
      setTimeout(() => {
        const values = this.form.getFieldsValue();
        if (values.startTime) {
          if (values.termYear) {
            if (e === 1) {
              // 年
              values.endTime = this.afterYear(values.startTime, values.termYear);
            }
            if (e === 2) {
              // 月
              values.endTime = this.afterMonth(values.startTime, values.termYear);
            }
            // if (e === 3) {
            //   values.endTime = afterTime(values.startTime, values.termYear);
            // }
          }
        }
        this.form.setFieldsValue({ ...values });
      });
    },
    change2() {
      setTimeout(() => {
        const values = this.form.getFieldsValue();
        if (values.termYear && values.startTime) {
          values.endTime = null;
          if (values.timeLimitType === 1) {
            values.endTime = this.afterYear(values.startTime, values.termYear);
          } else if (values.timeLimitType === 2) {
            values.endTime = this.afterMonth(values.startTime, values.termYear);
          }
        }
        this.form.setFieldsValue({ ...values });
      });
    },
    afterMonth(now, num) {
      const t = this.moment(now).add(num, "month").subtract(1, "day");
      return t;
    },
    afterYear(now, num) {
      const t = this.moment(now).add(num, "years").subtract(1, "day");
      return t;
    },
    getMoment(date) {
      return date ? this.moment(date) : null;
    },
    getDisabled(v) {
      let b = false;
      v ? (b = true) : (b = false);
      return b;
    },
    changeType(e) {
      this.show = e !== "laborContractUnlimit";
    }
  }
};
</script>

<style lang="scss" scoped>
.f-box {
  width: 100%;
  padding: 40px 128px 32px 128px;
  background: rgba(255, 255, 255, 0);
  box-shadow: 0px 6px 16px 8px rgba(0, 0, 0, 0.03), 0px 4px 8px 0px rgba(0, 0, 0, 0.04);
  border-radius: 4px;
  ::v-deep .ant-form-item-label {
    font-size: 14px;
    font-family: SourceHanSansCN-Regular, SourceHanSansCN;
    font-weight: 400;
    color: #55565d;
  }
}
</style>
